
//
// 120727 - AH - (Midtun) Created.
//

package org.soekrat.server.serialization;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *   Base class for 
 *   {@link Serializable} with string/value parameters in form of
 *   {@link ParameterSerializable}.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public abstract class ParametersSerializable implements Serializable 
{
  protected final List<ParameterSerializable> m_parameters=
    new ArrayList<ParameterSerializable>();
  
  /**
   * <p>
   *   Sets parameter.
   * </p>
   * @param name  Parameter name.
   * @param value Parameter value.
   * @return {@code this}.
   */
  public final ParametersSerializable parameter(String name, String value)
  {
    if (name==null)
    {
      throw new NullPointerException("name");
    }
    if (value==null)
    {
      throw new NullPointerException("value");
    }
    
    int idx=findParameterIndex(name);
    if (idx==-1)
    {
      m_parameters.add(new ParameterSerializable(name, value));
      return this;
    }
    
    m_parameters.get(idx).value(value);
    return this;
  }
  
  /**
   * <p>
   *   Gets number of parameters.
   * </p>
   * @return Count.
   */
  public final int getParameterCount(){ return m_parameters.size(); }
  
  /**
   * <p>
   *   Gets
   *   {@link ParameterSerializable parameter}.
   * </p>
   * @param idx Index of parameter to get.
   * @return Parameter.
   */
  public final ParameterSerializable parameter(int idx)
  {
    return m_parameters.get(idx);
  }
  
  private int findParameterIndex(String name)
  {
    int n=getParameterCount();
    for (int i=0; i<n; i++)
    {
      ParameterSerializable curr=m_parameters.get(i);
      if (name==curr.name || name.equals(curr.name)) return i;
    }
    return -1;
  }
  
}
